#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

int countLines(const char *filename) {
   char c;
   int ret;
   FILE *in = fopen(filename, "r");
   c = getc(in);
   while(c != EOF) {
      if(c == '\n')
         ret++;
      c = getc(in);
   }
   fclose(in);
   return ret;
}

void countBases(const char *filename, char ***bases){
   FILE *in = fopen(filename, "r");
   int temp = 0;
   int len = 0;
   int lengths[6];
   int number = 0;
   char c = getc(in);
   int i = 0;
   while(c != EOF) {
      len++;
      if(c == '\n') {
         lengths[temp-1] = len - 1;
         bases[number] = malloc(temp * sizeof(char*));
         for(i = 0; i < temp; i++) {
          bases[number][i] = malloc(lengths[i] * sizeof(char));
         }
         number++;
         temp = 0;
         len = 0;
      }
      if(c == ' ') {
         if(temp > 0)
            lengths[temp-1] = len -1;
         temp++;
         len = 0;
      }
      c = getc(in);
   } 
   fclose(in);  
}

void addWords(const char *filename, char ***bases){
   FILE *in = fopen(filename, "r");
   char c = getc(in);
   char dummy[100];
   int word = 0, number = 0, len = 0;
   while(c != EOF) {
      if(number%5000 == 0)
         printf("%d\n", number);
      if(c == ' ') {
         dummy[len] = 0;
         if(word > 0)
            strcpy(bases[number][word-1], dummy);
         word++;
         len = 0;
         c = getc(in);
         continue;
      }
      if(c == '\n') {
         dummy[len] = 0;
         strcpy(bases[number][word-1], dummy); 
         number++;
         word = 0;
         len = 0;
         c = getc(in);
         continue;
      }
      dummy[len++] = c;
      c = getc(in);
   }
   fclose(in);
}


int main() {
   char *morfo = "morfo3.txt";
   int m = countLines(morfo);
   
   char ***bases;
   bases = malloc(m*sizeof(char**));
   
   int *counter;
   counter = malloc(m * sizeof(int));
   
   countBases(morfo, bases);
   
   addWords(morfo, bases);
      
   return 0;
}
